﻿package{
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	import flash.filters.*;
	
	import ascb.display.DraggableSprite;
	
	public class Main extends Sprite {
		private var _red:DraggableSprite;
		private var _green:DraggableSprite;
		private var _blue:DraggableSprite;
		private var _white:DraggableSprite;
		
		private var startingLocation:Point;
		
		public function Main() {
			createRectangles();
			addEventListeners();
		}
		
		private function createRectangles():void{
			_red = new DraggableSprite
			_red.graphics.beginFill(0xff0000);
			_red.graphics.drawRoundRect( 0, 10, 10, 10, 2, 2 );
			_red.graphics.endFill();
			
			_green = new DraggableSprite
			_green.graphics.beginFill(0x00ff00);
			_green.graphics.drawRoundRect( 0, 30, 10, 10, 2, 2 );
			_green.graphics.endFill();
			
			_green = new DraggableSprite
			_green.graphics.beginFill(0x0000ff);
			_green.graphics.drawRoundRect( 0, 50, 10, 10, 2, 2 );
			_green.graphics.endFill();
			
			_white = new DraggableSprite
			_white.graphics.beginFill(0xffffff);
			_white.graphics.drawRoundRect( 20, 10, 10, 10, 2, 2 );
			_white.graphics.endFill();
		}
		
		private function addEventListeners():void{
			_red.addEventListener(MouseEvent.MOUSE_DOWN, pickup);
			_red.addEventListener(MouseEvent.MOUSE_UP, place);
			
			_green.addEventListener(MouseEvent.MOUSE_DOWN, pickup);
			_green.addEventListener(MouseEvent.MOUSE_UP, place);
			
			_blue.addEventListener(MouseEvent.MOUSE_DOWN, pickup);
			_blue.addEventListener(MouseEvent.MOUSE_UP, place);
		}
		
		public function pickup(event:MouseEvent):void{
			startingLocation = new Point();
			startingLocation.x = event.target.x;
			startingLocation.y = event.target.y;
			
			event.target.drag();
			event.target.filters = [ new DropShadowFilter() ];
			
			setChildIndex(DisplayObject(event.target), numChildren - 1);
		}
		
		public function place( event:MouseEvent):void {
			event.target.drop();
			event.target.filters = null;
			
			var dropTargets:Array = getObjectsUnderPoint (new Point(mouseX, mouseY));
			
			if(dropTargets [ dropTargets.length - 2 ] == _white) {
				var color:uint;
				switch(event.target) {
					case _red: color = 0xFF0000; break;
					case _green:color = 0x00ff00; break;
					case _blue:color = 0x0000ff; break;
				}
				
				_white.graphics.clear();
				_white.graphics.beginFill(color);
				_white.graphics.drawRoundRect( 20, 10, 10, 10, 2, 2 );
			}
			
			event.target.x = startingLocation.x;
			event.target.y = startingLocation.y;
		}
		
		
		
	}
}
											